package scenetracer.util;
import java.util.LinkedList;
import scenetracer.core.Primitive;
import scenetracer.core.Scene;
import scenetracer.core.primitive.Box;
import scenetracer.core.primitive.OctreeNode;
import scenetracer.core.primitive.Triangle;
import scenetracer.core.primitive.TriangleMesh;
import scenetracer.math.BoundingBox;
import scenetracer.math.Point3;

public class Octree {

	public Primitive makeOctree(TriangleMesh mesh, int nTriangles){
        BoundingBox rBox = new BoundingBox(mesh);
        rBox.setShaders(mesh.getShaders());
        OctreeNode rNode = new OctreeNode(rBox,nTriangles);
        rNode.box.mesh = mesh;
        rNode.createOctTreeNoDepth(rNode);
        return rNode;
	}
	
	public static boolean triangleMatchThisBox(BoundingBox b, Triangle t){
		Point3 [] points = t.getPoints();
		
		if(b.isInside(points[0]) || b.isInside(points[1]) || b.isInside(points[2])){
			return true;
		}
		if(b.intersects(t)){
			return true;
		}
		return false;
	}
	
	public Scene makeOctree(Scene container,int nTriangles){
		LinkedList<Primitive> octree = new LinkedList<Primitive>();
		
		for (Primitive object : container.getPrimitives()) {
			if (object instanceof Box){
				octree.add(object);
			}
			else if (object instanceof TriangleMesh) {
				octree.add(makeOctree((TriangleMesh)object,nTriangles));
			}else{
				octree.add(object);
			}
		}
		container.setPrimitives(octree);
		return container;
	}
}
